/*
 *                                                     __----~~~~~~~~~~~------___
 *                                    .  .   ~~//====......          __--~ ~~
 *                    -.            \_|//     |||\\  ~~~~~~::::... /~
 *                 ___-==_       _-~o~  \/    |||  \\            _/~~-
 *         __---~~~.==~||\=_    -_--~/_-~|-   |\\   \\        _/~
 *     _-~~     .=~    |  \\-_    '-~7  /-   /  ||    \      /
 *   .~       .~       |   \\ -_    /  /-   /   ||      \   /
 *  /  ____  /         |     \\ ~-_/  /|- _/   .||       \ /
 *  |~~    ~~|--~~~~--_ \     ~==-/   | \~--===~~        .\
 *           '         ~-|      /|    |-~\~~       __--~~
 *                       |-~~-_/ |    |   ~\_   _-~            /\
 *                            /  \     \__   \/~                \__
 *                        _--~ _/ | .-~~____--~-/                  ~~==.
 *                       ((->/~   '.|||' -_|    ~~-/ ,              . _||
 *                                  -_     ~\      ~~---l__i__i__i--~~_/
 *                                  _-~-__   ~)  \--______________--~~
 *                                //.-~~~-~_--~- |-------~~~~~~~~
 *                                       //.-~~~--\
 *                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * 
 *                               神兽保佑            永无BUG
 * 
 * Author : gezhigang
 * Date   : 2020-05-21 16:47:00
 */
import Axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosPromise, AxiosStatic } from 'axios'
import { Message } from 'element-ui'
import { isString, isObject, getToken } from '@/libs/utils'

class JFHttpRequest {
    constructor() {
        let host = process.env.VUE_APP_HOST
        this.baseUrl = host ? host : ''
    }
    /**
     * 超时-时间
     */
    timeout = 1e3 * 60 * 3
    /**
     * 基础路径
     */
    baseUrl = ''
    /**
     * 请求参数
     */
    options = {
        method: '',
        url: ''
    }
    /**
     * 请求队列
     */
    queue: {
        [index: string]: any
    } = {};

    private destroy(url: string): number {
        delete this.queue[url]
        const queue = Object.keys(this.queue)
        return queue.length
    }
    /**
     * 请求拦截器
     * @param instance Axios实例对象
     * @param url 地址
     */
    interceptors(instance: AxiosInstance, url: string): void {
        instance.interceptors.request.use((config: AxiosRequestConfig) => {
            return config
        }, error => {
            return Promise.reject(error)
        })

        instance.interceptors.response.use((res: AxiosResponse): any => {
            this.destroy(url)
            const { data } = res
            //登录失效，重新登录
            if (data.code === 1006) {
                Message.warning(data.msg)
            }
            return data
            
        }, (error: any) => {
            if (error.response) {
                let status = error.response.status
                if (status === 404) {
                    Message.error('接口 Not Found')
                }
                // 服务端错误
                if (status === 500) {
                    let data = error.response.data
                    Message.error('服务内部错误！')
                }
            }
            this.destroy(url)
            return Promise.reject(error)
        })
    }
    /**
     * 创建Axios实例
     */
    create(config: AxiosRequestConfig): AxiosInstance {
        if (!isObject(config)) {
            config = {}
        }
        let axiosConfig = Object.assign({
            baseURL: this.baseUrl,
            timeout: this.timeout,
            headers: {
                'Content-Type': 'application/json; charset=utf-8',
                'Authorization':'Bearer '+ getToken()
            }
        }, config)
        return Axios.create(axiosConfig)
    }
    /**
     * 发送请求
     * @param options axios参数相同
     */
    request(options: any, axiosConfig: AxiosRequestConfig = {}): Promise<YQCX.Response> {
        var instance:any = this.create(axiosConfig)
        if (isString(options)) {
            options = {
                url: options
            }
        }
        this.interceptors(instance, options.url)
        options = Object.assign({}, options)
        this.queue[options.url] = instance
        return instance(options)
    }

    'get'(url: string, params?: any) {
        return this.request({
            url: url,
            method: 'GET',
            params: params
        })
    }

    post(url: string, data?: any){
        return this.request({
            url: url,
            method: 'POST',
            data: data
        })
    }

    axios(options: any): AxiosPromise<any> {
        return Axios(options)
    }
}
export interface YQCXHttp {
    /**
     * 发送请求
     * @param options axios参数相同
     */
    request(options: any, axiosConfig?: AxiosRequestConfig): Promise<YQCX.Response>;
    /**
     * 发送请求
     * @param options get参数相同
     */
    get(url: string, params?: any) : Promise<YQCX.Response>;
    /**
     * 发送请求
     * @param options post参数相同
     */
    post(url: string, data?: any) : Promise<YQCX.Response>;
    /**
     * 发送axios请求 参考 http://www.axios-js.com/docs/#axios-get-url-config
     */
    axios: AxiosStatic ;
}

export default new JFHttpRequest()
